package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/adapter"
	"os"
	"strings"
	"time"
	"weiboxs.com/new_h_glasses/enums"
	"weiboxs.com/new_h_glasses/models"
	"weiboxs.com/new_h_glasses/services"
	"weiboxs.com/new_h_glasses/utils"
)

type WechatController struct {
	BaseController
}

func (c *WechatController) Prepare() {
	c.BaseController.Prepare()
}

func (c *WechatController) Setings() {

	c.checkAuthor("wechat/setings") //需要权限控制
	c.Data["activeSidebarUrl"] = "/wechat/setings"

	s := models.WechatSetings{}
	if c.Ctx.Input.IsPost() { //提交
		data := make(map[string]string)
		if err := c.Ctx.Input.Bind(&data, "conf"); err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		}
		if err := s.SaveSetings(data, c.curUser); err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		}
		c.jsonResult(enums.JRCodeSucc, "配置信息保存成功", "")
	}
	c.Data["data"] = s.GetSetings(false)

	c.display()
}

//自定义菜单
func (c *WechatController) SetMenu() {

	c.checkAuthor("wechat/setmenu") //需要权限控制
	c.Data["activeSidebarUrl"] = "/wechat/setmenu"

	wechatModel := &models.WechatMenu{}

	lists := wechatModel.All(c.curUser)
	c.Data["lists"] = lists

	c.display("", "wechat/setmenu_footerjs.html")
}

//编辑菜单
func (c *WechatController) EditMenu() {

	c.checkAuthor("wechat/editmenu") //需要权限控制
	wechatModel := &models.WechatMenu{}
	wechatModel.Orderby = 100
	if c.Ctx.Input.IsPost() { //保存数据
		if err := c.ParseForm(wechatModel); err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		}

		if err := wechatModel.Save(c.curUser); err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		}
		c.jsonResult(enums.JRCodeSucc, "菜单保存成功", "")
	}
	id, _ := c.GetInt64(":id")
	parent_id, _ := c.GetInt64("pid")
	wechatModel.ParentId = parent_id
	if id > 0 {
		wechatModel = wechatModel.Get(id,c.curUser)
	}

	c.Data["m"] = wechatModel
	c.display("wechat/editmenu.html", "", "shared/layout_dialog.html")
}

//删除菜单
func (c *WechatController) DelMenu() {
	id, _ := c.GetInt64("id")
	if id == 0 {
		c.jsonResult(enums.JRCodeFailed, "参数传递错误", "")
	}
	wechatModel := &models.WechatMenu{}
	if err := wechatModel.Del(id, c.curUser); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "菜单删除成功", "")
}

//生成菜单
func (c *WechatController) CreateMenu() {
	ser := services.WechatApiService{}
	if err := ser.CreateMenus(c.curUser); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "ok", "")
}

//消息列表
func (c *WechatController) Message() {

	c.checkAuthor("wechat/message")

	if c.Ctx.Input.IsPost() {
		var params models.WechatMessageParam
		model := models.WechatMessage{}
		json.Unmarshal(c.Ctx.Input.RequestBody, &params)
		params.DepartmentId = c.curUser.DepartmentId
		data, total := model.MessagePageList(&params)
		c.jsonDataTable(total, data)
		return
	}
	c.Data["activeSidebarUrl"] = "/wechat/message"

	c.display("", "wechat/message_footerjs.html")
}

//消息增减
func (c *WechatController) EditMessage() {
	c.checkAuthor("wechat/edit_message")

	model := &models.WechatMessage{}
	if c.Ctx.Input.IsPost() { //保存数据
		id, _ := c.GetInt64("Id")
		if id > 0 {
			model = model.One(id, c.curUser.DepartmentId)
		}
		model.DepartmentId = c.curUser.DepartmentId
		if err := c.ParseForm(model); err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		}
		model.RelationIds = c.GetString("RelationIds")

		if err := model.Save(c.Ctx.Input.Site()); err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		}
		c.jsonResult(enums.JRCodeSucc, "消息保存成功", "")
	}

	id, _ := c.GetInt64(":id")
	model.Typeid = 1;
	if id > 0 { //查询一条数据
		model = model.One(id, c.curUser.DepartmentId)
	}

	c.Data["m"] = model
	c.Data["activeSidebarUrl"] = "/wechat/message"
	c.display("", "wechat/editmessage_footerjs.html")
}

//消息删除
func (c *WechatController) DelMessage() {
	c.checkAuthor("wechat/del_message")
	model := &models.WechatMessage{}
	id, _ := c.GetInt64("id")
	if id <= 0 {
		c.jsonResult(enums.JRCodeSucc, "参数错误", "")
	}
	if err := model.Del(id, c.curUser); err != nil {
		c.jsonResult(enums.JRCodeSucc, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "ok", "")
}

//编辑器图片上传
func (c *WechatController) EditorUpload() {

	var inputId string = "inputImageUrl"
	f, h, err := c.GetFile(inputId)
	if err != nil {
		c.jsonResult(enums.JRCodeFailed, fmt.Sprintf("上传失败：%s", err.Error()), "")
	}
	defer f.Close()

	extSplit := strings.Split(h.Filename, ".")

	ext := strings.ToLower(extSplit[len(extSplit)-1])

	allowExt := map[string]int{"jpg": 1, "png": 1, "jpeg": 1, "gif": 1}
	if _, ok := allowExt[ext]; !ok {
		c.jsonResult(enums.JRCodeFailed, "上传失败，不是可用的文件", "")
	}

	var filename string = fmt.Sprintf("%d_%d_%s.%s", c.curUser.Id, time.Now().Day(), utils.RandomString(6), ext)
	filePath := fmt.Sprintf("/static/message/%d/%d", time.Now().Year(), int(time.Now().Month()))

	if err := os.MkdirAll(beego.AppPath+filePath, os.ModePerm); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}

	var fullUrl = filePath + "/" + filename
	c.SaveToFile(inputId, beego.AppPath+fullUrl)
	c.jsonResult(enums.JRCodeSucc, "上传成功", c.Ctx.Input.Site()+fullUrl)
}

//粉丝列表
func (c *WechatController) Follows() {
	c.checkAuthor("wechat/binduser")

	if c.Ctx.Input.IsPost() {
		var params models.WechatFollowsQueryParam
		json.Unmarshal(c.Ctx.Input.RequestBody, &params)
		params.DepartmentId = c.curUser.DepartmentId
		data, total := models.WechatFollowsPageList(&params)
		c.jsonDataTable(total, data)
		return
	} else {
		c.Data["activeSidebarUrl"] = "/wechat/follows"
		c.display("", "wechat/follows_footerjs.html")
	}
}
